package Bai06;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPserver {

	/**
	 * @param args
	 * 
	 */
	DatagramSocket socket;
	public UDPserver(int port){
		try {
			socket=new DatagramSocket(port);
			System.out.println("Server is running!");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	public void run(){
		FileReader fr;
		FileWriter fw;
		BufferedReader br;
		DatagramPacket dp;
		int f=1;
		byte[] buf=new byte[1024];
		try {	
			do{
				fr=new FileReader("login.txt");
				br=new BufferedReader(fr);
				dp=new DatagramPacket(buf, buf.length);
				socket.receive(dp);
				String str=new String(dp.getData(),0,dp.getLength());
				String[] send=str.split("&&");
				switch (send[2]) {
				case "btnRegister":
					while(br.ready()){
						String string=br.readLine();
						String subStart=string.substring(0, string.indexOf("&&"));
						if(subStart.equals(send[0])){
							f=0;
							break;
						}
					}
					if(f==1){
						fw=new FileWriter("login.txt", true);
						fw.write("\r\n");
						fw.write(send[0]+"&&"+send[1]);
						fw.close();
					}
					break;
				case "btnSignin":
					while(br.ready()){
						String string=br.readLine();
						String subStart=string.substring(0, string.indexOf("&&"));
						String subEnd=string.substring(string.indexOf("&&")+2,string.length());
						if(subStart.equals(send[0])){
							if(subEnd.equals(send[1]))
								f=0;
							else f=2;
							break;
						}
					}
					
					break;
				}
				String strsend=f+"";
				dp=new DatagramPacket(strsend.getBytes(), strsend.length(), dp.getAddress(), dp.getPort());
				socket.send(dp);
				f=1;
			}while(true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		socket.close();
		System.out.println("Server is closed!");
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UDPserver server=new UDPserver(2048);
		server.run();
		
	}

}

